package com.vg.view;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vg.com.chatonline.activity.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnCloseListener;
import android.widget.TextView;
import ce51.dunghn.imagethread.ExtendedImageDownloader;

import com.dunghn.loadtest.JsonParse;
import com.kds.abs.app.SherlockFragment;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class OrtherFragment extends SherlockFragment implements
		SearchView.OnQueryTextListener {
	String url = "http://deduocyeu.com/json/getUserStatus.php?page=1&pagesize=20";
	ArrayList<HashMap<String, String>> contact;
	ContactAdapter adapter;
	private ListView lv;
	SearchView searchView;
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options;

	@SuppressLint("NewApi")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.stub_image)
				.showImageForEmptyUri(R.drawable.image_for_empty_url)
				.cacheInMemory().cacheOnDisc()
				.bitmapConfig(Bitmap.Config.RGB_565).build();

		View v = inflater.inflate(R.layout.listview_ya, null);
		lv = (ListView) v.findViewById(R.id.listview);
		searchView = (SearchView) v.findViewById(R.id.ya_searchView);
		searchView.setQueryHint("Find friend");
		searchView.setOnQueryTextListener(this);
		searchView.setOnCloseListener(new OnCloseListener() {

			public boolean onClose() {
				// TODO Auto-generated method stub
				adapter.notifyDataSetChanged();
				lv.setAdapter(adapter);
				return false;
			}
		});

		contact = new ArrayList<HashMap<String, String>>();
		contact = loadContactData(url);
		adapter = new ContactAdapter(getActivity(), contact);
		lv.setAdapter(adapter);
		return v;
	}

	public static SherlockFragment newinstance() {
		return new OrtherFragment();

	}

	// Khi thay doi ky tu o searchview, update listview cho moi lan thay doi
	public boolean onQueryTextChange(String arg0) {
		// TODO Auto-generated method stub
		String str = searchView.getQuery().toString().toLowerCase();
		if (!str.equals("")) {
			ArrayList<HashMap<String, String>> contact_sort = new ArrayList<HashMap<String, String>>();
			contact_sort.clear();
			for (int i = 0; i < contact.size(); i++) {
				String s = contact.get(i).get("use_fullname").toLowerCase();
				boolean b = s.contains(str);
				Log.i("Test", b + "");
				if (b) {
					contact_sort.add(contact.get(i));
				}
			}
			lv.setAdapter(new ContactAdapter(getActivity(), contact_sort));
		}

		return true;
	}

	public boolean onQueryTextSubmit(String arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	// Tra ve list ban be tu json data
	public ArrayList<HashMap<String, String>> loadContactData(String url) {
		ArrayList<HashMap<String, String>> contact_list = new ArrayList<HashMap<String, String>>();
		JSONArray data = new JSONArray();
		JsonParse js = new JsonParse();
		JSONObject jso = new JSONObject();
		jso = js.getJSONFromUrl(url);
		try {
			data = jso.getJSONArray("data");
			for (int i = 0; i < data.length(); i++) {
				JSONObject obj = data.getJSONObject(i);
				String name = obj.getString("use_fullname");
				String image = obj.getString("use_avatar");
				HashMap<String, String> arr = new HashMap<String, String>();
				arr.put("use_fullname", name);
				arr.put("use_avatar", image);

				contact_list.add(arr);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return contact_list;
	}

	// Adapter cho listview hien thi danh sach ban be
	public class ContactAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		Context c;
		ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();

		public ContactAdapter(Context context,
				ArrayList<HashMap<String, String>> d) {
			c = context;
			data = d;
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return data.get(position);
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View vi = convertView;
			if (convertView == null) {
				vi = inflater.inflate(R.layout.custom_lv_contact, null);
			}
			TextView txtView = (TextView) vi
					.findViewById(R.id.contact_txt_name);
			ImageView imageView = (ImageView) vi
					.findViewById(R.id.contact_img_avatar);
			DisplayMetrics metrics=getActivity().getResources().getDisplayMetrics();
			int width=metrics.widthPixels;
			int height=metrics.heightPixels;
			
			LinearLayout.LayoutParams layout=new LinearLayout.LayoutParams(width/6, width/6);
			imageView.setLayoutParams(layout);

			txtView.setText(data.get(position).get("use_fullname"));
			ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
					getActivity().getApplicationContext())
					.threadPriority(Thread.NORM_PRIORITY - 2)
					.memoryCacheSize(2 * 1024 * 1024)
					.denyCacheImageMultipleSizesInMemory()
					.discCacheFileNameGenerator(new Md5FileNameGenerator())
					.imageDownloader(
							new ExtendedImageDownloader(getActivity()
									.getApplicationContext()))
					.tasksProcessingOrder(QueueProcessingType.LIFO)
					.enableLogging().build();
			ImageLoader.getInstance().init(config);
			imageLoader.displayImage(data.get(position).get("use_avatar"),
					imageView, options);

			return vi;
		}
	}

}
